<template>
  <div class="pledge">
    <!-- 质押详情 -->
    <div class="flex flex-center mt-20 mb-10">
      <div class="title title--bg">{{ $t('质押详情') }}</div>
    </div>

    <div>
      <div v-if="details.length">
        <ul class="data-list">
          <li class="box flex lh-2 mt-10" v-for="(v, i) in details" :key="i">
            <!-- <div class="item">
              <span class="label">用户</span>
              <span class="value">{{ v.user_id }}</span>
            </div> -->
            <div class="item">
              <span class="label">{{ $t('总质押额') }}</span>
              <span class="value">{{ v.amount_all }}</span>
            </div>
            <!-- <div class="item">
              <span class="label">有效质押额</span>
              <span class="value">{{ v.amount_real }}</span>
            </div> -->
            <div class="item">
              <span class="label">{{ $t('获取收益倍数') }}</span>
              <span class="value">{{ v.amount_times }}</span>
            </div>
            <div class="item">
              <span class="label">{{ $t('退场额') }}</span>
              <span class="value">{{ v.amount_exit }}</span>
            </div>
            <div class="item">
              <span class="label">{{ $t('日化收益率') }}(%)</span>
              <span class="value">{{ (v.rate_year / 365).toFixed(2) }}</span>
            </div>
            <div class="item">
              <span class="label">{{ $t('总收益') }}</span>
              <span class="value">{{ v.interest }}</span>
            </div>
            <div class="item">
              <span class="label">{{ $t('用户收益') }}</span>
              <span class="value">{{ v.profit_pr }}</span>
            </div>
            <!-- <div class="item">
              <span class="label">用户A收益</span>
              <span class="value">{{ v.profit_pa }}</span>
            </div>
            <div class="item">
              <span class="label">用户B收益</span>
              <span class="value">{{ v.profit_pb }}</span>
            </div> -->
            <div class="item">
              <span class="label">{{ $t('客户分红') }}</span>
              <span class="value">{{ v.agent_bonus }}</span>
            </div>
            <div class="item">
              <span class="label">{{ $t('团队奖励') }}</span>
              <span class="value">{{ v.team_rewards }}</span>
            </div>
            <!-- <div class="item">
              <span class="label">提现额20%</span>
              <span class="value">{{ v.withdraw_pa }}</span>
            </div>
            <div class="item">
              <span class="label">提现额80%</span>
              <span class="value">{{ v.withdraw_pb }}</span>
            </div> -->
            <!-- <div class="item">
              <span class="label">上阶段总收益额</span>
              <span class="value">{{ v.stage_all }}</span>
            </div> -->
            <div class="item">
              <span class="label">{{ $t('上阶段期次') }}</span>
              <span class="value">{{ v.stage_batch }}</span>
            </div>
            <!-- <div class="item">
              <span class="label">上阶段用户收益</span>
              <span class="value">{{ v.stage_profit }}</span>
            </div> -->
            <!-- <div class="item">
              <span class="label">上阶段代理收益</span>
              <span class="value">{{ v.stage_agent }}</span>
            </div>
            <div class="item">
              <span class="label">上阶段团队收益</span>
              <span class="value">{{ v.stage_team }}</span>
            </div> -->
            <!-- <div class="item">
              <span class="label">创建时间</span>
              <span class="value">{{ formatDateTime(v.create_time) }}</span>
            </div> -->
            <div class="item">
              <span class="label">{{ $t('更新时间') }}</span>
              <span class="value">{{ formatDateTime(v.update_time) }}</span>
            </div>
          </li>
        </ul>

        <!-- 分页 -->
        <van-pagination
          class="mt-10"
          mode="simple"
          :prev-text="$t('上一页')"
          :next-text="$t('下一页')"
          :total-items="total1"
          :items-per-page="size1"
          @change="getDetails"
          v-model="page1"
        ></van-pagination>
      </div>

      <van-empty :description="$t('暂无数据')" v-else></van-empty>
    </div>

    <div class="box flex flex-cc pt-15 pb-15 mt-10">
      <van-field
        class="mr-10"
        type="digit"
        :placeholder="RATE_TIPS"
        :border="false"
        v-model="amount"
      ></van-field>
      <van-button class="btn" type="primary" @click="pledge">
        {{ $t('质押') }}
      </van-button>
    </div>

    <!-- 质押规则 -->
    <!-- <div>
      <div class="flex flex-center mt-20">
        <div class="title title--bg">质押规则</div>
      </div>

      <div class="box">
        <ul class="table">
          <li class="table__th">
            <div class="table__td">质押额</div>
            <div class="table__td">日化率</div>
            <div class="table__td">退场倍数</div>
          </li>

          <li class="table__tr" v-for="(v, i) in rules" :key="i">
            <div class="table__td">{{ v.low }}-{{ v.high }} U</div>
            <div class="table__td">{{ (v.rate / 365).toFixed(2) }}%</div>
            <div class="table__td">{{ v.times }}</div>
          </li>
        </ul>
      </div>
    </div> -->

    <!-- 质押订单 -->
    <div>
      <div class="flex flex-center mt-20">
        <div class="title title--bg">{{ $t('质押订单') }}</div>
      </div>

      <div v-if="orders.length">
        <ul class="data-list">
          <li class="box lh-2 mt-10" v-for="(v, i) in orders" :key="i">
            <div class="item">
              <span class="label">{{ $t('金额') }}</span>
              <span class="value">{{ v.order_amount || 0 }} USDT</span>
            </div>
            <div class="item">
              <span class="label">{{ $t('状态') }}</span>
              <span class="value">{{ v.status }}</span>
            </div>
            <div class="item">
              <span class="label">{{ $t('时间') }}</span>
              <span class="value">{{ formatDateTime(v.create_time) }}</span>
            </div>
          </li>
        </ul>

        <!-- 分页 -->
        <van-pagination
          class="mt-10"
          mode="simple"
          :prev-text="$t('上一页')"
          :next-text="$t('下一页')"
          :total-items="total2"
          :items-per-page="size2"
          @change="getOrders"
          v-model="page2"
        ></van-pagination>
      </div>

      <van-empty :description="$t('暂无数据')" v-else></van-empty>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useStore } from '@/store/index'
import { useI18n } from 'vue-i18n'
import {
  showToast,
  showSuccess,
  showError,
  showLoading,
  toNumber,
  toBigNumber,
  formatDateTime,
} from 'js/utils'
import apis from 'js/apis'

const store = useStore()
const { t } = useI18n()

// 质押金额倍数
const RATE_AMOUNT = ref(0)

// 质押金额倍数提示
const RATE_TIPS = computed(() => {
  // return t('请输入', { amount: RATE_AMOUNT.value })
  return t('请输入')
})

// 质押金额
const amount = ref(null)

// 质押规则
const rules = ref([])

// 质押详情
const details = ref([])
const page1 = ref(1)
const size1 = ref(2)
const total1 = ref(0)

// 质押订单
const orders = ref([])
const page2 = ref(1)
const size2 = ref(5)
const total2 = ref(0)

const loading = ref(null)

watch(
  () => store.config,
  () => {
    if (store.config.length) {
      const real_times = store.config.find((v) => v.name === 'real_times') || {
        value: 100,
      }
      RATE_AMOUNT.value = real_times.value
    }
  },
  {
    immediate: true,
    deep: true,
  }
)

getDetails()
getRules()
getOrders()

// 质押
async function pledge() {
  try {
    // if (!amount.value || amount.value % RATE_AMOUNT.value !== 0) {
    //   return showToast(RATE_TIPS.value)
    // }

    // if (amount.value >= 500 && amount.value < 5000) {
    //   const min = (amount.value / store.xmPrice) * 0.2
    //   if (window.pandax < min) {
    //     return showToast(t('门槛', { min }))
    //   }
    // } else if (amount.value >= 5000 && amount.value < 10000) {
    //   const min = (amount.value / store.xmPrice) * 0.3
    //   if (window.pandax < min) {
    //     return showToast(t('门槛', { min }))
    //   }
    // } else if (amount.value >= 10000) {
    //   const min = (amount.value / store.xmPrice) * 0.4
    //   if (window.pandax < min) {
    //     return showToast(t('门槛', { min }))
    //   }
    // }

    let amountUsdt = amount.value
    let amountPandax = 0

    if (amount.value <= 500) {
      amountUsdt = amount.value
      amountPandax = 0
    } else if (amount.value <= 5000) {
      amountUsdt = amount.value * 0.8
      amountPandax = (amount.value / store.xmPrice) * 0.2
    } else if (amount.value <= 10000) {
      amountUsdt = amount.value * 0.7
      amountPandax = (amount.value / store.xmPrice) * 0.3
    } else {
      amountUsdt = amount.value * 0.6
      amountPandax = (amount.value / store.xmPrice) * 0.4
    }

    loading.value = showLoading()

    // 判断用户Usdt授权给Order的额度是否足够，不够就先授权额度
    const authorizedBalanceByUsdt = await getAuthorizedBalanceByUsdt()

    if (authorizedBalanceByUsdt <= 0) {
      // 需要授权额度
      await authorizeBalanceByUsdt()
    } else if (authorizedBalanceByUsdt < amountUsdt) {
      // 可用额度小于用户投资的金额
      await authorizeBalanceByUsdt()
    }

    // 判断用户Pandax授权给Order的额度是否足够，不够就先授权额度
    if (amountPandax) {
      const authorizedBalanceByPandax = await getAuthorizedBalanceByPandax()

      if (authorizedBalanceByPandax <= 0) {
        // 需要授权额度
        await authorizeBalanceByPandax()
      } else if (authorizedBalanceByPandax < amountPandax) {
        // 可用额度小于用户投资的金额
        await authorizeBalanceByPandax()
      }
    }

    // 投资金额
    await investAmount()

    loading.value?.close()
  } catch (err) {
    console.error(err)
    loading.value?.close()
  }
}

// 投资金额
function investAmount() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log(`投资金额：${amount.value}`)
      const res = await orderContract.context.methods
        .invest(toBigNumber(amount.value))
        .send({
          from: fromAddress,
        })
      amount.value = null
      showSuccess(t('质押成功'))
      console.log('质押成功')
      console.log(res)
      resolve(res)
    } catch (err) {
      amount.value = null
      showError(t('质押失败'))
      console.error('质押失败')
      console.error(err)
      reject(err)
    }
  })
}

// Usdt授权Order额度
function authorizeBalanceByUsdt() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(50000) // 授权 50000 Usdt额度
      const res = await usdtContract.context.methods
        .approve(orderContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess(t('授权余额成功'))
      console.log(`授权Usdt余额成功：${toNumber(quota)}`)
      console.log(res)
      resolve(quota)
    } catch (err) {
      showError(t('授权余额失败'))
      console.error('授权Usdt余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取Usdt授权给Order的额度
function getAuthorizedBalanceByUsdt() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await usdtContract.context.methods
        .allowance(fromAddress, orderContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取Usdt授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError('获取授权余额失败')
      console.error('获取Usdt授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// Pandax授权Order额度
function authorizeBalanceByPandax() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(50) // 授权 50 Pandax额度
      const res = await pandaxContract.context.methods
        .approve(orderContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess(t('授权余额成功'))
      console.log(`授权Pandax余额成功：${toNumber(quota)}`)
      console.log(res)
      resolve(quota)
    } catch (err) {
      showError(t('授权余额失败'))
      console.error('授权Pandax余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取Pandax授权给Order的额度
function getAuthorizedBalanceByPandax() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await pandaxContract.context.methods
        .allowance(fromAddress, orderContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取Pandax授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError('获取授权余额失败')
      console.error('获取Pandax授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取质押详情
async function getDetails() {
  const params = {
    page: page1.value,
    limit: size1.value,
  }

  const { code, data } = await apis.pledge.getDetails(params)

  if (code === 1) {
    let records = data.data || []
    records = records.filter((v) => v.contract_status == 1)
    details.value = records
    total1.value = data.count || 0
  }
}

// 获取质押规则
async function getRules() {
  const params = {
    loading: false,
  }

  const { code, data } = await apis.pledge.getRules(params)

  if (code === 1) {
    rules.value = data
  }
}

// 获取质押订单
async function getOrders() {
  const params = {
    page: page2.value,
    limit: size2.value,
  }

  const { code, data } = await apis.pledge.getOrders(params)

  if (code === 1) {
    orders.value = data.data || []
    total2.value = data.count || 0
  }
}
</script>

<style lang="scss" scoped>
.btn {
  width: 120px;
}
</style>
